var express = require('express');
var app = express();
var http = require('http').Server(app);
var bodyParser = require('body-parser');
var session = require('express-session');
var net = require('net');
var iconv = require('iconv-lite');
var car = require('./tcpClient_car_data.js');
const child_process = require('child_process');
var log_start = require('../lib/log_start.js');
var fs = require('fs');
// 变量
var file_buf = fs.readFileSync(__dirname + '/server_admin/image/car1.jpeg');
 //console.log(file_buf.length); 6989
var HOST = car.config.host;
var PORT = car.config.port;
var time = car.config.time;
var key = "regist";
var client = new net.Socket();
// 终端发送命令
function command_buf(){   
        console.log(key);          
        if (key == 'media') {
            var arr = car.data[key].split(" ");
            // var len = 1+16+(36+987)+1+1;//消息的总长度
            var bao_count = Math.ceil(file_buf.length/987);
            // 分包发送
            for (var i = 0; i < bao_count; i++) {               
                var len2 = arr.length;
                var buf1 = Buffer.allocUnsafe(len2);
                var start = i*987;
                if (i == bao_count - 1) {
                    var end = file_buf.length - 1;
                }else{
                    var end = start + 987;
                }               
                for (var j = 0; j < arr.length; j++) {
                    var str = arr[j];                       
                    buf1[j] = parseInt('0x'+str);           
                }
                // 计算消息体属性
                var max = 8192;
                var body_len = 36+(end - start);
                var rel = max + body_len;
                buf1.writeInt16BE(rel, 3);   
                // 重置分包项信息
                buf1.writeInt16BE(bao_count, 13); 
                buf1.writeInt16BE(i+1, 15);
                // 第一次发送   
                // console.log(body_len, rel,buf1);            
                client.write(buf1);
                // 发送多媒体数据包                
                var buf2 = file_buf.slice(start, end);
                // 第二次发送 
                client.write(buf2);
                // 发送校验码 和 最后的标识位0x7e
                var buf3 = Buffer.allocUnsafe(2);
                // 计算校验位
                var jiaoyan = create_jiaoyan2(buf1,buf2);
                // console.log(jiaoyan);
                buf3[0] = jiaoyan;
                buf3[1] = 0x7e;
                // 第三次发送
                client.write(buf3);   
            }                        
        }else{
            var arr = car.data[key].split(" ");
            var len = arr.length;
            var buf = Buffer.allocUnsafe(len);
            for (var i = 0; i < arr.length; i++) {
                var str = arr[i];                       
                buf[i] = parseInt('0x'+str);           
            }
            var buf = create_jiaoyan(buf);                
            client.write(buf);
        }     
        // setTimeout(command_buf,time);  
        return buf;
}
// 校验码生成
function create_jiaoyan(buf){
    // console.log(buf);
    var result = buf[1];
    for (var j = 2; j < buf.length -2; j++) {
      //对每个字节进行异或运算
      result = result ^ buf[j];
    }
    buf[buf.length-2] = result;
    return buf;
}
// 校验码的生成
function create_jiaoyan2(buf1,buf2){
    var result = buf1[1];
    for (var i = 2; i < buf1.length; i++) {
        result = result ^ buf1[i];
    }
    for (var i = 0; i < buf2.length; i++) {
        result = result ^ buf2[i];
    }
    return result;
}
function closesocket(){
    // client.end();
    console.log("please close me");
}
client.connect(PORT, HOST, function () {
    console.log('CONNECTED TO: ' + HOST + ':' + PORT);
    // Write a message to the socket as soon as the client is connected, the server will receive it as message from the client 
    //client.write('I am Chuck Norris!');
    // command_buf();
});

// Add a 'data' event handler for the client socket
// data is what the server sent to this socket
client.on('data', function (data) {
    // console.log('data',data);
    //client.destroy();
});

// Add a 'close' event handler for the client socket
client.on('close', function () {
    console.log('Connection closed');
});

/* 
 功能：子进程接收父进程的消息
  接收到信息后设置，控制协议
*/
process.on('message', (m) =>{
    // console.log('CHILD got message:', m);
    key = m.key;
    time = m.time;
    command_buf();
});
/* 
 功能：子进程向父进程发送信息 
*/
function process_send(data){
    process.send(
          data
    );
}










